package com.srzk.youthleagueback.service;

import com.srzk.youthleagueback.mapper.UserMapper;
import com.srzk.youthleagueback.pojo.User;
import com.srzk.youthleagueback.results.CodeMsg;
import com.srzk.youthleagueback.results.Result;
import com.srzk.youthleagueback.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;


    /**
     * 根据用户名获得用户信息
     *
     * @param userName
     * @return
     */
    public User getByUserName(String userName) {

        return userMapper.getByUserName(userName);

    }

    /**
     * 登录
     *
     * @param userName
     * @param formPass
     * @return 登录成功的用户名
     */
    public Result<String> login(String userName, String formPass) {


        //判断用户是否存在
        User user = getByUserName(userName);
        if (user == null) {
            //用户为空时返回错误：用户名不存在
            return Result.error(CodeMsg.USERNAME_NOT_EXIST);
        }

        //如果查询存在该用户名的用户，则验证密码
        String formPassAfterMD5 = MD5Util.formPassToDBPass(formPass);
        if (!formPassAfterMD5.equals(user.getPassword())) {
            //密码错误异常
            return Result.error(CodeMsg.PASSWORD_ERROR);
        }


        return Result.success(userName);
    }

    /**
     * 添加用户
     *
     * @param user
     */
    public void setUser(User user) {
        userMapper.setUser(user);
    }
}
